package com.dcits.common;


import org.jasypt.encryption.StringEncryptor;
import org.springframework.security.crypto.password.PasswordEncoder;

public class JasyptPasswordEncoder implements PasswordEncoder {

    protected final StringEncryptor encryptor;

    public JasyptPasswordEncoder(StringEncryptor encryptor) {
        this.encryptor = encryptor;
    }

    @Override
    public String encode(CharSequence rawPassword) {
        // 加密密码，格式为 ENC(加密后的密码)
        return "ENC(" + encryptor.encrypt(rawPassword.toString()) + ")";
    }

    /**
     * 解密字符串
     *
     * @param encryptedText 加密文本，格式应为 ENC(加密结果)
     * @return 解密后的原始文本
     */
    public String decrypt(String encryptedText) {
        if (isEncrypted(encryptedText)) {
            return encryptor.decrypt(extractEncryptedValue(encryptedText));
        }
        return encryptedText;
    }

    /**
     * 检查是否为加密值
     */
    public boolean isEncrypted(String value) {
        return value != null && value.startsWith("ENC(") && value.endsWith(")");
    }

    /**
     * 从ENC包裹中提取加密值
     */
    private String extractEncryptedValue(String value) {
        return value.substring(4, value.length() - 1);
    }

    @Override
    public boolean matches(CharSequence rawPassword, String encodedPassword) {
        // 解密并比较密码
        if (encodedPassword.startsWith("ENC(") && encodedPassword.endsWith(")")) {
            String encryptedPassword = encodedPassword.substring(4, encodedPassword.length() - 1);
            String decryptedPassword = encryptor.decrypt(encryptedPassword);
            return rawPassword.toString().equals(decryptedPassword);
        }
        return false;
    }

}